<template>
  <div class="securityContent" id="securityContent">
    <!-- 功能按钮 -->
    <div class="top-button">
      <div class="securityContent_button">
        <a-button
          class="addButton"
          type="primary"
          :disabled="creatAble"
          @click="addRecord(1)"
        >
          <template #icon>
            <span class="iconfont icon-Add iconadd"></span>
          </template>
          新建
        </a-button>
      </div>
    </div>

    <!-- 表格展示部分 -->
    <treeTable
      :columns="columns.organizeManagesColumns"
      :dataSource="configData.records"
      :rowSelection="rowSelection"
      :isSelect="true"
      :scroll="scroll"
      ref="baseTables"
      :isShowPagination="isShowPagination"
      :defaultExpandAllRows="true"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'isFictitious'">
          {{ record.orgType === 0 ? "是" : "否" }}
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a
            class="eidtRecords"
            :class="{ disable: editAble }"
            @click="eidtRecord(record)"
            >{{ oparation[0] }}</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('orgAuthorityViewAble') || userStore.userInfo.orgId == record.id}"
            @click="setAuthRecord(record)"
            >{{ oparation[1] }}</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('personManageAble') }"
            @click="memberRecord(record)"
            >{{ oparation[2] }}</a
          >
          <span v-if="!(!record.authAble && !record.parentId)">
            <a-popconfirm
              v-if="record.children"
              :disabled="deleteAble || userStore.userInfo.orgId == record.id "
              placement="topRight"
              ok-text="我知道了"
              :showCancel="false"
            >
              <template #title>
                <p style="width: 197px">该组织下还存在子组织，请先移除后再删除组织</p>
              </template>
              <a :class="{ disable: deleteAble || userStore.userInfo.orgId == record.id  }">{{ oparation[3] }}</a>
            </a-popconfirm>
            <a-popconfirm
              v-else
              :disabled="deleteAble || userStore.userInfo.orgId == record.id"
              placement="topRight"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmDelete(record)"
            >
              <template #title>
                <p style="width: 197px">是否删除该组织，删除后不可恢复</p>
              </template>
              <a :class="{ disable: deleteAble || userStore.userInfo.orgId == record.id }">{{ oparation[3] }}</a>
            </a-popconfirm>
          </span>
          <a v-else :disabled="true" style="color: rgba(0, 0, 0, 0.25)">{{
            oparation[3]
          }}</a>
        </template>
      </template>
    </treeTable>

    <!-- 新建人员组织模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
      v-if="isVisible"
      class="securitycontent_modal"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          autoComplete="off"
          class="ant-advanced-search-form"
          :model="formState"
          ref="contentFrom"
        >
          <a-form-item
            :label="formState.upOrg.label"
            :name="['upOrg', 'value']"
            :rules="[formState.upOrg.rule]"
            v-if="
              (formState.upOrg.value || formState.orgType) &&
              formState.upOrg.value !== null
            "
          >
            <a-tree-select
              v-model:value="formState.upOrg.value"
              ref="usermanage_treeSelect"
              show-search
              :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
              allow-clear
              treeNodeFilterProp="name"
              :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
              tree-default-expand-all
              :tree-data="treeData"
              placeholder="请选择"
              @change="changeContent"
            >
            </a-tree-select>
          </a-form-item>
          <a-form-item
            :name="['orgName', 'value']"
            :label="formState.orgName.label"
            :rules="[formState.orgName.rule]"
          >
            <a-input
              v-model:value="formState.orgName.value"
              placeholder="请输入组织名称"
              show-count
              :maxlength="25"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :name="['orgNum', 'value']"
            :label="formState.orgNum.label"
            :rules="[formState.orgNum.rule]"
          >
            <a-input
              v-model:value="formState.orgNum.value"
              placeholder="请输入"
              style="width: 256px"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :name="['orgLeader', 'value']"
            :label="formState.orgLeader.label"
            :rules="[formState.orgLeader.rule]"
          >
            <a-input
              v-model:value="formState.orgLeader.value"
              placeholder="请输入"
              style="width: 256px"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :name="['orgPhone', 'value']"
            :label="formState.orgPhone.label"
            :rules="[formState.orgPhone.rule]"
          >
            <a-input
              v-model:value="formState.orgPhone.value"
              placeholder="请输入"
              style="width: 256px"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            :name="['orgFax', 'value']"
            :label="formState.orgFax.label"
            :rules="[formState.orgFax.rule]"
          >
            <a-input
              v-model:value="formState.orgFax.value"
              placeholder="请输入"
              style="width: 256px"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            class="tag-item"
            :label="formState.orgRemark.label"
            :rules="[formState.orgRemark.rule]"
          >
            <a-textarea
              style="position: relative; width: 508px"
              v-model:value="formState.orgRemark.value"
              placeholder="请输入组织描述"
              show-count
              :maxlength="50"
            />
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import treeTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/columnsName";
import baseModal from "@/components/modal/baseModal.vue";
import { useRouter } from "vue-router";
import { Modal, message } from "ant-design-vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import tableToolTip from "@/components/table/tableToolTip.vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { checkCreatSiteForm, checkOrgFaxForm } from "./formRuler";
import getOptions from "@/utils/getRelationOptions";
import { cloneDeep } from "lodash";
import { object } from "vue-types";
import { routerPerm } from "@/utils/common";
import { useUserStore } from "@/store/modules/user";
// type
type configDataType = {
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
interface FormState {
  tagWord: dataSourceType;
  password: string;
  remember: boolean;
}

//data
const userStore = useUserStore()
const btnPerm = ref<any[]>([]);
const creatAble = ref<any>(false);
const creatVirAble = ref<any>(false);
const editAble = ref<any>(false);
const deleteAble = ref<any>(false);
const router = useRouter();
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = false; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
//表格数据
let configData = reactive<configDataType>({ records: [] });
let rowSelection = ref<string | number>(1);
const upOrgOptions = ref([]);
const treeData = ref<dataSourceType[]>();
const upOrgOptions_f = ref<configDataType[]>([]);
// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新加、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const oparation = ref<string[]>(["编辑", "权限设置", "成员管理", "删除"]); //站点表格操作项
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建组织",
});
const contentFrom = ref<any>("contentFrom");

let formState = reactive<dataSourceType>({
  upOrg: {
    value: undefined,
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "上级组织不能为空！",
    },
    label: "上级组织",
  },
  orgName: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "组织名称不能为空！",
    },
    label: "组织名称",
  },
  orgNum: {
    value: "",
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "",
    },
    label: "组织编号",
  },
  orgLeader: {
    value: "",
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "",
    },
    label: "负责人",
  },
  orgPhone: {
    value: "",
    rule: {
      required: false,
      validator: checkCreatSiteForm,
      msg: "请输入正确的组织电话！",
      trigger: ["blur"],
      type: "phone",
    },
    label: "组织电话",
  },
  orgFax: {
    value: "",
    rule: {
      required: false,
      trigger: ["blur"],
      msg: "仅支持输入数字！",
      validator: checkOrgFaxForm,
      type: "orgFax",
    },
    label: "组织传真",
  },
  orgRemark: {
    value: "",
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "",
    },
    label: "组织描述",
  },
  parentId: "",
  orgType: "1",
  id: "",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
//methods
const addRecord = async (type: number) => {
  //新加组织模态框条件修改
  //添加组织数据
  if (type == 0) {
    //
    modAlProps.title = "新建虚拟组织";
  } else {
    modAlProps.title = "新建组织";
  }
  let keys = Object.keys(formState);
  keys.forEach((item) => {
    if (typeof formState[item] != "object") {
      formState[item] = "";
    } else {
      formState[item].value = undefined;
    }
  });
  //formState.orgPhone.rule.validator = checkCreatSiteForm;
  modAlProps.title = type === 1 ? "新建组织" : "新建虚拟组织";
  treeData.value = getOptions("", JSON.parse(JSON.stringify(upOrgOptions_f.value)));
  isVisible.value = true;
  isAddOrEdit.value = true;
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];

  nextTick(() => {
    formState.orgType = type;
    contentFrom.value.resetFields();
  });
};
const eidtRecord = async (item: dataSourceType) => {
  //编辑组织管理数据
  if (editAble.value) return;
  const data = await request.fetchOrganizeDetail({ id: item.id });
  if (item.orgType === 0) {
    modAlProps.title = "编辑虚拟组织";
  } else {
    modAlProps.title = "编辑组织";
  }
  treeData.value = getOptions(item.id, JSON.parse(JSON.stringify(upOrgOptions_f.value)));
  formState.orgName.value = data.name;
  formState.orgFax.value = data.orgFax;
  formState.orgLeader.value = data.orgLeader;
  formState.orgNum.value = data.orgNum;
  formState.orgRemark.value = data.orgRemark;
  formState.upOrg.value = data.parentId || null;
  formState.orgPhone.value = data.phone;
  formState.id = data.id;
  isAddOrEdit.value = true;
  isVisible.value = true;
  nextTick(() => {
    contentFrom.value.resetFields();
  });
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};
const setAuthRecord = async (item: dataSourceType) => {
  if (!btnPerm.value.includes("orgAuthorityViewAble") || userStore.userInfo.orgId == item.id) return;
  //前往权限设置
  router.push({
    path: "/system/organizeManages/permissionSettings",
    name: "组织权限设置",
    query: {
      orgId: item.id,
      orgType: item.orgType,
      name: item.name,
    },
  });
};
const memberRecord = async (item: dataSourceType) => {
  if (!btnPerm.value.includes("personManageAble")) return;
  //前往成员管理
  router.push({
    path: "/system/organizeManages/memberManage",
    name: "成员管理",
    query: {
      id: item.id,
      orgType: item.orgType,
    },
  });
};
const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑组织调取接口
  //保存
  contentFrom.value
    .validate()
    .then(() => {
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
      const params = {
        name: formState.orgName.value,
        id: formState.id,
        orgFax: formState.orgFax.value,
        orgLeader: formState.orgLeader.value,
        orgNum: formState.orgNum.value,
        orgRemark: formState.orgRemark.value,
        parentId: formState.upOrg.value || formState.parentId || null,
        orgType: formState.orgType,
        phone: formState.orgPhone.value,
      };

      request[type === "Edit" ? "fetchOrganizeUpdate" : "fetchOrganizeAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            //geUserorgs();
            getRdecord();
            getSelectOption();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = msg.text == "保存" ? false : true;
    })
    .catch(() => {});
};
const confirmDelete = async (item: any) => {
  // 删除单个组织
  if (!item.deleteAble) {
    message.error("主组织不可删除！");
    return;
  }
  deleteRecords(item.id);
};
const changeContent = (e: string, options: any) => {
  //获取上级组织id
  formState.upOrg.value = e;
  formState.parentId = options.id;
};
const deleteRecords = async (id: number) => {
  // 调接口删除组织
  await request.fetchOrganizeDelete({ id }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRdecord({});
      getSelectOption();
    } else {
      message.error(res.message);
    }
  });
};
const getRdecord = async (datas: dataSourceType = {}) => {
  // 获取表格数据
  const postData: {} = {};
  const data = (await request.fetchUserOrgTree(postData)) || {};
  let reqData = data;
  configData.records = reqData;
  upOrgOptions.value = reqData;
  nextTick(() => {
    scroll.y = getTableScroll(74, "searchWord").y;
    scroll.isFixed = getTableScroll(74, "searchWord").isFixed;
  });
};
const getSelectOption = async () => {
  //获取下拉选择列表
  const postData: {} = {
    // 不传参数默认所有
  };
  const data = (await request.fetchOrganizeChildTree(postData)) || {};
  let reqData = data;
  upOrgOptions_f.value = reqData;
};

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm();
  routerPerm().includes("creatAble")
    ? (creatAble.value = false)
    : (creatAble.value = true);
  routerPerm().includes("creatVirAble")
    ? (creatVirAble.value = false)
    : (creatVirAble.value = true);
  routerPerm().includes("editAble") ? (editAble.value = false) : (editAble.value = true);
  routerPerm().includes("deleteAble")
    ? (deleteAble.value = false)
    : (deleteAble.value = true);
  getRdecord();
  getSelectOption();
});
</script>
<style lang="scss" scoped>
.securityContent {
  width: 100%;
  height: calc(100% - 72px);
  padding: 24px;
  background-color: #fff;
  overflow: hidden;

  .top-button {
    display: flex;
    flex-direction: row;
    padding-bottom: 24px;
    align-items: center;

    .securityContent_button {
      display: flex;

      .addButton {
        display: flex;
        align-items: center;
        margin-right: 8px;

        .iconadd {
          font-size: 24px;
          margin-right: 4px;
        }
      }

      .importButton {
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
        margin-right: 8px;
      }

      .searchContent {
        margin-left: auto;
        margin-right: 0px;
      }
    }
  }

  ::v-deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
.model-tip {
  margin-top: 8px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
}

.tag-item {
  margin-bottom: 0 !important;
}

::v-deep(.ant-form-item) {
  width: 604px;
  display: flex;

  .ant-form-item-control {
    width: 248px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 80px;
    text-align: right;
  }
}

::v-deep(.ant-table-body) {
  max-height: 554px !important;
}

::v-deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-number) {
  width: 136px;
  margin-left: 4px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 508px;
}

::v-deep(.ant-input-textarea-show-count::after) {
  position: absolute;
  right: 12px;
  bottom: 26px;
}

::v-deep(.ant-form-item .ant-select, .ant-form-item .ant-cascader-picker) {
  width: 508px;
}
</style>
